<template>
  <div class="code-list">

    <AdminList title="管理员" :adminList="adminList" />


    <TableForm :initial-form="form" @query="query" @reset="resetForm" :total="total" @current-change="currentChange"
      @size-change="sizeChange" ref="tableFormRef">

      <template #form-items>
        <el-form-item>
          <el-input class="common-input" v-model="form.name" placeholder="请输入国家名称" clearable></el-input>
        </el-form-item>
      </template>

      <template #add-button>
        <el-button @click="dialogVisible = true" class="add-country-button"
          v-if="hasPermissionOrRole('CountryManagement.New', 1, 1)">
          <img class="plus" src="@/assets/images/svg/plus.png" alt="" />
          新增国家
        </el-button>
      </template>

      <!-- 下方表格区域 -->
      <template #table>
        <CommonTable :table-data="tableData" :max-height="630">
          <el-table-column type="index" label="序号" width="100"></el-table-column>
          <el-table-column label="排序号" prop="sortNo">
            <template #default="scope">
              {{ scope.row.isActive ? scope.row.sortNo : "--" }}
            </template>
          </el-table-column>

          <el-table-column label="国家名称" prop="name"></el-table-column>
          <el-table-column label="地区号" prop="areaCode"></el-table-column>

          <el-table-column width="400" label="是否激活" prop="isActive" v-if="userStore.userInfo.userRoleType == 1">
            <template #default="scope">
              <!-- 启用国家状态弹窗 -->
              <el-switch style="--el-switch-on-color: #2258F6; --el-switch-off-color: #d9d9d9"
                v-model="scope.row.isActive" @change="updateStatus(scope.row)"></el-switch>
            </template>
          </el-table-column>

          <!-- 右侧操作按钮区域 -->
          <el-table-column width="150" label="操作" prop="operate"
            v-if="hasPermissionOrRole('CountryManagement.List', 1, 1)">
            <template #default="scope">
              <div class="operation">
                <!-- 上移 -->
                <div v-if="scope.row.isActive" class="detail detail-option" @click="move(scope.row, true)">
                  <span class="movetext">上移</span>
                </div>
                <!-- 下移 -->
                <div v-if="scope.row.isActive" class="detail detail-option" @click="move(scope.row, false)">
                  <span class="movetext">下移</span>
                </div>
              </div>
            </template>
          </el-table-column>

        </CommonTable>
      </template>

    </TableForm>

  </div>



  <!-- 新增国家弹窗 -->
  <el-dialog title="新增国家/地区" align-center v-model="dialogVisible" width="410" class="common-dialog"
    @open="resetAddForm">

    <el-form class="common-form-inline" ref="addFormRef" :model="addForm" :rules="rules" label-width="auto">
      <el-form-item label="国家/地区" prop="code">
        <el-select v-model="addForm.code" class="common-select">
          <el-option v-for="item in allCountryList" :key="item.code" :label="item.name" :value="item.code"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="是否启用" prop="isActive">
        <el-radio-group v-model="addForm.isActive" class="common-radio">
          <el-radio :value="true">是</el-radio>
          <el-radio :value="false">否</el-radio>
        </el-radio-group>
      </el-form-item>

    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false" class="cancel-button">取消</el-button>
        <el-button style="background: #2258F6; color: #fff;" class="confirm-button" @click="submit" :loading="loading">
          确认
        </el-button>
      </div>
    </template>

  </el-dialog>


</template>

<script setup lang="ts">
import iconWarning from "@/assets/img/svg/icon-warning.svg";
import TableForm from '@/components/TableForm/index.vue';
import CommonTable from '@/components/CommonTable/index.vue';
import { type CountryListType } from "@/type/countryType";
import usePermissionHasAccess from '@/hooks/permissionHasAccess';
import { AdminEnum } from '@/enum/admin'
import AdminList from '@/components/AdminList.vue'
import { getCountryList, moveCountry, updateCountry, AddCountry, getEffectiveCountry } from '@/apis/country'
import { getAdminList } from '@/apis/admin'
import { useAdminStore } from '@/stores/adminStore';

import type { Action, FormInstance, FormRules } from "element-plus";

import { ElMessageBox } from "element-plus";

import { ref, h, onMounted } from 'vue'
import { errorTips, successTips } from "@/utils/utils";
import { useUserStore } from '@/stores/user';
const userStore = useUserStore();

const { hasPermissionOrRole } = usePermissionHasAccess();

interface CountryData {
  countryId: number;
  code: string;
  name: string;
  isActive: boolean;
  areaCode: string;
  sortNo: number;
  recordsTotal: number;
}

const adminStore = useAdminStore()
const tableFormRef = ref<any>(null)
const tableData = ref<CountryData[]>([])

type Form = {
  pageIndex: number;
  pageSize: number;
  sortField: string;
  sortOrder: string;
  name: string;
};

const form = ref<Form>({
  pageIndex: 1,
  pageSize: 50,
  sortField: "countryId",
  sortOrder: "desc",
  name: "",
});

//表单数据总数量
const total = ref(0);


//点击启用禁用国家功能
const updateStatus = (item: CountryListType) => {
  let isActive = item.isActive;
  let msg = "";
  let title = "";
  if (item.isActive) {
    isActive = true;
    title = '启用国家/地区';
    msg = "确认要启用此国家/地区么？";

  } else {
    isActive = false;
    title = "禁用国家/地区";
    msg = "确认要禁用此国家/地区么？";
  }
  ElMessageBox.confirm(msg, {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: "warning",
    icon: h("img", {
      class: "warning-icon",
      src: iconWarning,
    }),
  }).then(() => {
    updateCountry({
      countryId: item.id,
      isActive
    }).then((res) => {
      query();
    });
  }).catch(() => {
    query();
  });
};



//移动国家功能
const move = async (item: any, isUp: boolean) => {
  moveCountry({ isUp, countryId: item.id, sortNo: item.sortNo }).then(res => {
    query()
  })
};


//查询调用相关方法
const query = async () => {
  try {
    const res = await getCountryList(form.value)
    if (res && res.data) {
      if (tableFormRef.value) {
        tableFormRef.value.updateTotal(res.data.count);
      }
      tableData.value = res.data.data;
      tableData.value = tableData.value.sort((a, b) => {
        if (a.isActive && b.isActive) {
          return a.sortNo - b.sortNo;
        } else if (a.isActive) {
          return -1;
        } else if (b.isActive) {
          return 1;
        } else {
          return a.sortNo - b.sortNo;
        }
      });
    }
  } catch (error) {
    errorTips('获取国家列表数据失败')
  }
}


//表单切换相关方法
const resetForm = () => {
  form.value.name = "";
  query();
};

const currentChange = (val: number) => {
  form.value.pageIndex = val;
  query();
};


const sizeChange = (val: number) => {
  form.value.pageSize = val;
  query();
};


//新增国家逻辑功能实现
const addFormRef = ref(null)
const dialogVisible = ref(false);

const addForm = ref({
  code: "",
  isActive: true,
  areaCode: "",
});

const loading = ref(false);

const rules = ref<FormRules>({
  code: [
    {
      required: true,
      trigger: "blur",
      message: "请选择国家",
    },
  ],
});




//新增国家提交事件
const submit = () => {
  addFormRef.value.validate((valid, fields) => {
    if (valid) {
      loading.value = true;
      // 映射areaCode
      const selectedCountry = allCountryList.value.find(item => item.code === addForm.value.code);
      if (selectedCountry) {
        addForm.value.areaCode = selectedCountry.areaCode;
      }

      AddCountry(addForm.value)
        .then((res) => {

          if (res.code === 1) {

            successTips('新增国家成功')
            dialogVisible.value = false;
            query();

          }
        })
        .catch((error) => {
          errorTips('新增国家失败')
        })
        .finally(() => {
          loading.value = false;
        });
    }
  });
};


/**
 * 重置添加表单数据
 */
const resetAddForm = () => {
  addForm.value = {
    code: "",
    isActive: true,
    areaCode: "",
  };
  //如果表单实例存在，则重置表单的验证状态
  if (addFormRef.value) {
    addFormRef.value.resetFields();
  }
};


//获取国家有效列表数据
const allCountryList = ref<any>([]);
const getSelectList = () => {
  getEffectiveCountry().then((res) => {
    allCountryList.value = res.data;
  });
};



query()
getSelectList()



const adminList = ref([])
//获取国家页面的管理员数据
const getAdmin = async () => {
  try {
    const res = await getAdminList({ menuId: AdminEnum.COUNTRY_MANAGEMENT })
    if (res && res.data) {
      adminList.value = res.data
    } else {
      adminList.value = []
    }
  } catch (error) {
    errorTips('获取管理员列表失败')
    adminList.value = []
  }
}


onMounted(() => {
  getAdmin()
  query()
  getSelectList()
})


</script>

<style scoped lang="scss">
.code-list {
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  background: #fff;
  padding: 15px 20px;

  .operation {
    display: flex;
    justify-content: flex-start;
    margin-bottom: 10px;
  }

  .add-country-button {
    width: 108px;
    height: 32px;
    font-size: 14px;
    color: #fff;
    background: #2258F6;
    border-radius: 2px;

    .plus {
      width: 16px;
      height: 16px;
      margin-right: 10px;
    }
  }

  .detail,
  .reset-psw,
  .disable {
    cursor: pointer;
    margin-right: 25px;
  }

  .detail {
    cursor: pointer;
    margin-right: 16px;
  }



}

.common-input {
  width: 190px;
  height: 32px;
  margin-right: 40px;
}

.movetext {
  font-size: 14px;
  color: #2258F6;
}
</style>
